package com.wy.thread_safe.locks_demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 美女
 * @date 2022/04/25 17:08
 *
 **/
public class Main4 {
    private static final Lock lock=new ReentrantLock();
    static class MyThread extends Thread{
        @Override
        public void run() {
            boolean b=lock.tryLock();
            if(b==true){
                //加锁成功了
                System.out.println("加锁成功");
                System.out.println("子线程进入临界区");
            }else {
                System.out.println("加锁失败");
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        lock.lock();//主线程已锁上
        MyThread t=new MyThread();
        t.start();
        TimeUnit.SECONDS.sleep(2);
        t.interrupt();
        t.join();
    }
}
//try.lock()尝试加锁，返回false加锁失败，true加锁成功
//由于这个代码主线程已经锁上，所以子线程一定是加锁失败的